package com.notebook.utils;

import com.notebook.entity.vo.news.LuceneNewsVo;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件描述:
 * 创建用户:emotion
 * 创建时间:2018/4/10
 */
public class LuceneUtil {

    private static Directory directory;


    //写索引
    public static boolean IndexWrite(String indexDir,List<LuceneNewsVo> list){
        boolean yesno = false;
        try {
            directory = FSDirectory.open(Paths.get(indexDir));
            IndexWriter writer = getWriter();
            for (LuceneNewsVo item:list) {
                Document doc = new Document();
                doc.add(new IntField("id",item.getNewsId(), Field.Store.YES));
                doc.add(new TextField("title",item.getTitle(),Field.Store.YES));
                doc.add(new TextField("newsKey",item.getNewsKey(),Field.Store.YES));
                writer.addDocument(doc);
                yesno=true;
            }
            writer.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return yesno;
    }


    //获取写索引
    private static IndexWriter getWriter()throws Exception{
        SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        IndexWriter writer = new IndexWriter(directory,config);
        return writer;
    }

    //搜索关键字
    public static List<LuceneNewsVo> search(String indexDir,String title){
        List<LuceneNewsVo> newIds = null;//创建返回集合
        try {
            newIds = new ArrayList<LuceneNewsVo>(0);
            Directory dir = FSDirectory.open(Paths.get(indexDir)); //获取索引文件实例
            IndexReader reader = DirectoryReader.open(dir);  //创建读取文件对象
            IndexSearcher searcher = new IndexSearcher(reader); //创建搜索文件对象
            SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer(); //创建中文分词器
            String[] fields = { "title", "newsKey" };
            BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
            Query query = MultiFieldQueryParser.parse(title, fields, clauses, analyzer);
            //读取前20条数据
            TopDocs hits=searcher.search(query, 20);
//            //设置高亮显示 start
//            QueryScorer scorer=new QueryScorer(query);
//            Fragmenter fragmenter=new SimpleSpanFragmenter(scorer);
//            SimpleHTMLFormatter simpleHTMLFormatter=new SimpleHTMLFormatter("<font color='red'>","</font>");
//            Highlighter highlighter=new Highlighter(simpleHTMLFormatter, scorer);
//            highlighter.setTextFragmenter(fragmenter);
            //endti
            for (ScoreDoc item :hits.scoreDocs) {
                Document document  =searcher.doc(item.doc);
                String id = document.get("id");
                String ti = document.get("title");
                String newsKey = document.get("newsKey");
//                if(ti!=null){
//
//                    TokenStream tokenStream=analyzer.tokenStream("title", new StringReader(ti));
//                    System.out.println(ti);
//                    ti = highlighter.getBestFragment(tokenStream, ti);
//                    System.out.println(ti);
//                }
                LuceneNewsVo newsVo = new LuceneNewsVo();
                newsVo.setNewsId(Integer.parseInt(id));

                newsVo.setTitle(ti);
                newsVo.setNewsKey(newsKey);
                newIds.add(newsVo);
            }

            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return newIds;

    }



}
